const express = require('express')
const expressWs = require('express-ws')
const app = express()

// 存储客户端连接
const clients = {
    sender: null,  // 发送方（共享屏幕）
    receiver: null // 接收方
}

expressWs(app)

app.ws('/websocket', (ws, req) => {
    console.log('新客户端连接')
    // 心跳检测
    const heartbeat = () => ws.pong(() => { })
    const heartbeatInterval = setInterval(heartbeat, 30000)
    // 客户端身份识别
    ws.on('message', (message) => {
        const data = JSON.parse(message)
        if (data.type === 'register') {
            if (data.role === 'sender' && !clients.sender) {
                clients.sender = ws
                console.log('发送方已注册')
            }
            else if (data.role === 'receiver' && !clients.receiver) {
                clients.receiver = ws
                console.log('接收方已注册')
                // 通知发送方开始协商
                if (clients.sender) {
                    clients.sender.send(JSON.stringify({ type: 'start_negotiation' }))
                }
            }
        }
        // 转发信令消息
        else if (data.target) {
            const target = data.target === 'sender' ? clients.sender : clients.receiver
            if (target) target.send(message)
        }
    })

    ws.on('close', () => {
        clearInterval(heartbeatInterval)
        if (ws === clients.sender) clients.sender = null
        if (ws === clients.receiver) clients.receiver = null
        console.log('客户端断开')
    })
})

app.listen(8080, () => {
    console.log('信令服务器运行在 ws://localhost:8080')
})